package lt.marsrutai.mobile.android.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import lt.marsrutai.mobile.android.exception.ClassInstantiationException;
import android.util.Log;

/**
 * Provides various convenience methods.
 * 
 * @author Justas
 */
public class ClassUtils {

    /**
     * Instantiates a class using it's default constructor.
     * 
     * @param clazz
     * @return
     */
    public static <T> T instantiateClass(Class<T> clazz) throws ClassInstantiationException {
        T taskFragment = null;
        
        try {
            taskFragment = clazz.newInstance();
        }
        catch (InstantiationException e) {
            throw new ClassInstantiationException("Could not instantiate class.", e);
        }
        catch (IllegalAccessException e) {
            throw new ClassInstantiationException("Default constructor is not visible.", e);
        }
        
        return taskFragment;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T invokeMethod(Object object, Method method, Object... params) {
        try {
            return (T) method.invoke(object, params);
        }
        catch (IllegalArgumentException e) {
            Log.w("ClassUtils", e.getMessage());
        }
        catch (IllegalAccessException e) {
            Log.w("ClassUtils", e.getMessage());
        }
        catch (InvocationTargetException e) {
            Log.w("ClassUtils", e.getMessage());
        }
        return null;// TODO fail silently?
    }
}
